<?php
// 从AI返回数据更新菜品信息和食材关联表

require_once '../thinkphp/base.php';

use think\Db;

/**
 * 更新菜品信息和食材关联
 * @param array $aiResponse AI返回的数据
 */
function updateDishInfoFromAI($aiResponse) {
    if (empty($aiResponse) || $aiResponse['code'] != 1) {
        echo "AI返回数据无效\n";
        return false;
    }
    
    $dishData = $aiResponse['data'];
    
    foreach ($dishData as $dishId => $dishInfo) {
        // 开始事务
        Db::startTrans();
        try {
            // 更新菜品信息
            $updateData = [
                'steps' => $dishInfo['steps'] ?? '',
                'cook_time' => $dishInfo['cook_time'] ?? '',
                'updatetime' => time()
            ];
            
            Db::name('food_dish')->where('id', $dishId)->update($updateData);
            
            // 删除原有的食材关联
            Db::name('food_ingredientrel')->where('dish_id', $dishId)->delete();
            
            // 添加新的食材关联
            if (!empty($dishInfo['ingredients'])) {
                $insertData = [];
                foreach ($dishInfo['ingredients'] as $index => $ingredient) {
                    // 只处理有效的食材（有ID的）
                    if (isset($ingredient['id']) && $ingredient['id'] > 0) {
                        $insertData[] = [
                            'dish_id' => $dishId,
                            'ingredient_id' => intval($ingredient['id']),
                            'quantity' => $ingredient['quantity'] ?? '100g',
                            'createtime' => time(),
                            'weigh' => $index + 1
                        ];
                    }
                }
                
                if (!empty($insertData)) {
                    Db::name('food_ingredientrel')->insertAll($insertData);
                    echo "为菜品ID {$dishId} 添加了 " . count($insertData) . " 个食材关联\n";
                }
            }
            
            // 标记为已调用AI
            Db::name('food_dish')->where('id', $dishId)->update(['ai_called' => 1]);
            
            // 提交事务
            Db::commit();
            echo "成功更新菜品ID {$dishId} 的信息\n";
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo "更新菜品ID {$dishId} 失败: " . $e->getMessage() . "\n";
            return false;
        }
    }
    
    return true;
}

/**
 * 模拟AI返回数据进行测试
 */
function testUpdateDishInfo() {
    $mockData = [
        'code' => 1,
        'msg' => '获取成功',
        'data' => [
            1 => [
                'ingredients' => [
                    ['id' => 1, 'name' => '鸡蛋', 'quantity' => '150克', 'unitEnergy' => 143],
                    ['id' => 2, 'name' => '西红柿', 'quantity' => '300克', 'unitEnergy' => 25]
                ],
                'cook_time' => '7分钟',
                'steps' => "1. 热锅凉油，倒入蛋液，中火煎至底部凝固后翻炒成块，盛出备用\n2. 锅中补少许油，爆香蒜末/葱白，下西红柿翻炒至出汁\n3. 加入炒好的鸡蛋，加盐、糖调味，翻炒均匀，可加少量水略焖\n4. 撒葱花，淋少许生抽（可选），翻炒出锅"
            ]
        ]
    ];
    
    updateDishInfoFromAI($mockData);
}

// 如果直接运行此脚本，则执行测试
if (basename(__FILE__) == basename($_SERVER['SCRIPT_NAME'])) {
    testUpdateDishInfo();
}

?>